package com.leo.foodmaster.admin.purchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.foodmaster.admin.purchase.entity.PurchaseBill;
import com.leo.foodmaster.admin.purchase.entity.Supplier;
import com.leo.foodmaster.admin.purchase.mapper.SupplierMapper;
import com.leo.foodmaster.admin.purchase.service.IPurchaseBillService;
import com.leo.foodmaster.admin.purchase.service.ISupplierService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leo.foodmaster.admin.system.entity.Organ;
import com.leo.foodmaster.admin.system.service.IOrganService;
import com.leo.foodmaster.commons.constants.HttpStatus;
import com.leo.foodmaster.commons.entity.Result;
import com.leo.foodmaster.commons.enums.OrganTypeEnum;
import com.leo.foodmaster.commons.exception.ImportException;
import com.leo.foodmaster.commons.util.WebUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 供应商 服务实现类
 * </p>
 *
 * @author Leo
 * @since 2021-07-31
 */
@Service
@AllArgsConstructor
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements ISupplierService {
    private final IOrganService organService;
    private final IPurchaseBillService purchaseBillService;

    /**
     * 条件分页查询供应商列表
     * @param page 分页条件
     * @param name 供应商名称
     * @param address 供应商地址
     * @param status 供应商状态
     * @return IPage<Supplier>
     */
    @Override
    public IPage<Supplier> getSupplierPageList(Page<Supplier> page, String name, String address, String status) {
        Long loginOrganId = WebUtils.getUser().getOrganId();
        String loginOrganType = WebUtils.getUser().getOrganType();
        Page<Supplier> pageList;

        if (OrganTypeEnum.PLATFORM.getCode().equals(loginOrganType)) {
            pageList = baseMapper.pageList(page, name, address, status);
        } else {
            LambdaQueryWrapper<Supplier> qw = Wrappers.lambdaQuery(Supplier.class)
                    .like(StrUtil.isNotBlank(name), Supplier::getName, name)
                    .like(StrUtil.isNotBlank(address), Supplier::getAddress, address)
                    .eq(StrUtil.isNotBlank(status), Supplier::getStatus, status)
                    .eq(Supplier::getSupplyOrganId, loginOrganId);
            pageList = page(page, qw);

        }
        return pageList;
    }

    /**
     * 新增供应商
     * @param supplier 供应商信息
     * @return Result<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> addSupplier(Supplier supplier) {
        Long loginOrganId = WebUtils.getUser().getOrganId();
        supplier.setSupplyOrganId(loginOrganId);
        // 根据供应商的名称和地址在公司表里查询，如果没有则新增公司
        Organ organ = organService.getOne(Wrappers.lambdaQuery(Organ.class)
                .eq(Organ::getName, supplier.getName())
                .eq(Organ::getAddr, supplier.getAddress()), false);
        if (BeanUtil.isNotEmpty(organ)) {
            supplier.setOrganId(organ.getId());
        } else {
            // 新增公司
            Organ newOrgan = new Organ();
            newOrgan.setName(supplier.getName());
            newOrgan.setAddr(supplier.getAddress());
            newOrgan.setType(OrganTypeEnum.SUPPLIER.getCode());
            newOrgan.setContactTel(supplier.getTel());
            organService.save(newOrgan);
            supplier.setOrganId(newOrgan.getId());
        }
        // 新增供应商
        save(supplier);
        return Result.success();
    }

    /**
     * 修改供应商
     * @param supplier 供应商信息
     * @return Result<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> updateSupplier(Supplier supplier) {
        // 修改供应商对应公司
        organService.update(Wrappers.lambdaUpdate(Organ.class)
                .set(Organ::getName, supplier.getName())
                .set(Organ::getAddr, supplier.getAddress())
                .set(Organ::getContactTel, supplier.getTel())
                .eq(Organ::getId, supplier.getOrganId()));
        // 修改供应商
        updateById(supplier);
        return Result.success();
    }

    /**
     * 导入供应商数据
     * @param supplierList 供应商列表
     * @param updateSupport 更新
     * @return String
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importSupplier(List<Supplier> supplierList, boolean updateSupport) {
        if (supplierList.isEmpty()) {
            throw new ImportException("导入用户数据不能为空！", HttpStatus.IMPORT_DATA_IS_EMPTY);
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Supplier supplier : supplierList) {
            try {
                // 验证是否存在该供应商
                Supplier supplierInDb = getOne(Wrappers.lambdaQuery(Supplier.class)
                        .eq(Supplier::getName, supplier.getName()));
                if (BeanUtil.isEmpty(supplierInDb)) {
                    addSupplier(supplier);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、供应商【 ").append(supplier.getName()).append("】导入成功");
                } else if (updateSupport) {
                    supplierInDb.setName(supplier.getName());
                    supplierInDb.setAddress(supplier.getAddress());
                    supplierInDb.setTel(supplier.getTel());
                    updateSupplier(supplierInDb);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、供应商【 ").append(supplier.getName()).append("】更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(successNum).append("、供应商【 ").append(supplier.getName()).append("】已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、供应商【" + supplier.getName() + "】导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ImportException(failureMsg.toString(), HttpStatus.IMPORT_FAILED);
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 删除供应商
     * @param id 供应商Id
     * @return 结果
     */
    @Override
    public Result<Object> deleteSupplier(Long id) {
        // 查询供应商有没有对应的采购单，如果有则不能删除
        List<PurchaseBill> list = purchaseBillService.list(Wrappers.lambdaQuery(PurchaseBill.class)
                .eq(PurchaseBill::getSupplierId, id));
        if (!list.isEmpty()) {
            return Result.fail("该供应商有对应的采购单，不能删除！");
        }
        // 删除供应商
        boolean b = removeById(id);
        return Result.success(b);
    }
}
